﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using System.Windows.Forms;

namespace FolderTreeViewer
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<FolderItem> RootItems { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            RootItems = new ObservableCollection<FolderItem>();
        }

        private async void BtnSelectFolder_Click(object sender, RoutedEventArgs e)
        {
            using (var dialog = new FolderBrowserDialog())
            {
                System.Windows.Forms.DialogResult result = dialog.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string selectedPath = dialog.SelectedPath;
                    await LoadFolderStructureAsync(selectedPath);
                }
            }
        }

        private async Task LoadFolderStructureAsync(string folderPath)
        {
            RootItems.Clear();
            FolderItem rootItem = new FolderItem(folderPath);
            await Task.Run(() => rootItem.EnsureChildrenLoaded());
            RootItems.Add(rootItem);
            rootItem.IsExpanded = false;
        }

        private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
        {
            if (sender is TreeViewItem treeViewItem)
            {
                if (treeViewItem.DataContext is FolderItem folderItem)
                {
                    folderItem.EnsureChildrenLoaded();
                }
            }
        }

        private void BtnExpandAll_Click(object sender, RoutedEventArgs e)
        {
            ExpandAll(RootItems);
        }

        private void ExpandAll(IEnumerable<FolderItem> items)
        {
            foreach (var item in items)
            {
                item.EnsureChildrenLoaded();
                item.IsExpanded = true;
                ExpandAll(item.Children);
            }
        }

        private void BtnCollapseAll_Click(object sender, RoutedEventArgs e)
        {
            CollapseAll(RootItems);
        }

        private void CollapseAll(IEnumerable<FolderItem> items)
        {
            foreach (var item in items)
            {
                CollapseAll(item.Children);
                item.IsExpanded = false;
            }
        }

        private void BtnSearch_Click(object sender, RoutedEventArgs e)
        {
            string searchText = TxtSearch.Text.Trim();
            if (string.IsNullOrEmpty(searchText))
            {
                System.Windows.MessageBox.Show("请输入搜索内容", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            SearchItems(RootItems, searchText);
        }

        private void SearchItems(IEnumerable<FolderItem> items, string searchText)
        {
            foreach (var item in items)
            {
                if (item.Name.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    item.IsSelected = true;
                    item.IsExpanded = true;
                    EnsureParentExpanded(item);
                }
                else
                {
                    item.IsSelected = false;
                }
                SearchItems(item.Children, searchText);
            }
        }

        private void EnsureParentExpanded(FolderItem item)
        {
            while (item != null)
            {
                item.IsExpanded = true;
                item = item.Parent;
            }
        }


        private void MenuItem_Open_Click(object sender, RoutedEventArgs e)
        {
            if (TreeViewFiles.SelectedItem is FolderItem folderItem)
            {
                if (File.Exists(folderItem.Path))
                {
                    OpenFile(folderItem.Path);
                }
                else if (Directory.Exists(folderItem.Path))
                {
                    OpenFolder(folderItem.Path);
                }
            }
        }

        private void OpenFile(string filePath)
        {
            try
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"无法打开文件 {filePath}: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OpenFolder(string folderPath)
        {
            try
            {
                System.Diagnostics.Process.Start("explorer.exe", folderPath);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"无法打开文件夹 {folderPath}: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}